package com.yzg.simple.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author misterWei
 * @mailbox mynameisweiyan@gmail.com
 *
 * NIO 网络传输介质
 * 结合 selector channel Buffer 组合使用 成立客户端
 */
public class NipClient {

    public static void main(String[] args) throws IOException {
        //获取一个与服务器进行链接的Channel
        SocketChannel socketChannel = SocketChannel.open();

        //设置非阻塞
        socketChannel.configureBlocking(false);

        //创建与服务器连接的信息
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1",8080);

        //该渠道进行绑定 并判断是否连接成功
         if (!socketChannel.connect(inetSocketAddress)){
             //绑定之后 如果没有成功
             while (! socketChannel.finishConnect()){
                 //也没有完成连接
                 System.out.println("未连接成功");
             }

         }

         //如果连接成功就发送数据
        String name = "魏岩";
        ByteBuffer byteBuffer = ByteBuffer.wrap(name.getBytes());
        socketChannel.write(byteBuffer);
        //阻塞到这里
        System.in.read();

    }
}
